<?php namespace app\api\controller;

use app\common\controller\AuthAndBind;
use think\Controller;
use think\Db;
use alisms\SendSms;
use esign\EsignHandle;

/**
 * api
 */
class Classification extends AuthAndBind{
	
	public function __construct(){
		parent::__construct();
	}
	
	/**
	 * 详情
	 */
	public function details(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				
				$data = Db::table("gd_classification") -> where($where) -> find();
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取分类详情',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 列表
	 */
	public function index(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where[] = ['is_delete', 'eq', 0];
				if( isset($in['create_date']) ) $where[] = ['create_date', 'between', $in['create_date']];
				if( isset($in['name']) ) $where[] = ['name', 'like', '%' . trim($in['name']) . '%'];
				if( isset($in['level']) ) $where[] = ['level', 'eq', trim($in['level'])];
				if( $userInfo['info']['type'] != 1 ) $where[] = ['id', 'not in', [4, 5]];
				if( isset($in['isGetRoutineGoods']) && $in['isGetRoutineGoods'] == 1 ) $where[] = ['id', 'not in', [4, 5]];
				
				$data = Db::table("gd_classification") -> where($where) -> order("sort asc") -> limit($start, $num) -> select();
				$count = Db::table("gd_classification") -> where($where) -> count();
				
				if( !empty($data) ) {
					foreach ($where as $k => $v) {
						if( $v[0] == 'level' ) unset($where[$k]);
					}
					$sonData = Db::table("gd_classification") -> where($where) -> order("sort asc") -> select();
					foreach ($sonData as $k => $v) {
						$sonData[$k]['parent_name'] = '';
						if( $v['parent_id'] > 0 ){
							foreach ($sonData as $kk => $vv) {
								if( $v['parent_id'] == $vv['id'] ) $sonData[$k]['parent_name'] = $vv['name'];
							}
						}
					}
					$sonData = $this -> tree($sonData);
					foreach ($data as $k => $v) {
						foreach ($sonData as $kk => $vv) {
							if( $v['id'] == $vv['id'] ) $data[$k] = $vv;
						}
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;				
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取分类列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 编辑
	 */
	public function edit(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_classification") -> where($where) -> find();
				if( empty($oldData) ) returnResults(['code'=>'-1', 'msg'=>'原数据有误']);
				
				$save = [];
				foreach ($in as $k => $v) {
					if( !in_array($k, ['id', 'user_id']) ){
						$save[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
					}
				}
				
				$save = filterArr($save, array_keys($save), $oldData);
				
				Db::startTrans();
				
//				排序字段存在
				if( isset($save['sort']) ){
					$checkSortWhere[] = ['level', 'eq', $oldData['level']];
					$checkSortWhere[] = ['parent_id', 'eq', $oldData['parent_id']];
					$checkSortWhere[] = ['sort', 'eq', $save['sort']];
					$checkSort = Db::table("gd_classification") -> where($checkSortWhere) -> find();
					if( !empty($checkSort) ){
						$sortWhere[] = ['level', 'eq', $oldData['level']];
						$sortWhere[] = ['parent_id', 'eq', $oldData['parent_id']];
						$all = Db::table("gd_classification") -> where($sortWhere) -> select();
						if( !empty($all) ){
	//						判断是否重叠
							foreach($all as $k => $v){
								if( $save['sort'] > $v['sort'] ) {
									unset($all[$k]);
								}else{
	//								重叠，后面的数据全部往后移动一位
									$incRe = Db::table("gd_classification") -> where(['id'=>$v['id']]) -> setInc('sort', 1);
									if( !$incRe ) {
										Db::rollback();
										returnResults2('-1', '变更排序失败,请联系管理员');
									}
								}
							}
						}
					}
				}else{
//					排序字段不存在，查询已有最大的排序值
//					$maxSort = Db::table("gd_classification") -> max("sort");
				}
				
				if( !empty($save) ){
					$re = Db::table("gd_classification") -> where($where) -> update($save);
					if( !$re ) {
						Db::rollback();
						returnResults2('-1', '编辑失败,请联系管理员');
					}
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'编辑分类',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 新增
	 */
	public function add(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$newData = [];
				foreach ($in as $k => $v) {
					if( in_array($k, ['name', 'sort', 'img', 'parent_id', 'level', 'icon']) ){
						$newData[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
					}
					$newData['create_user_id'] = $in['user_id'];
					$newData['create_user_name'] = $userInfo['info']['nickname'];
					$newData['create_date'] = date("Y-m-d H:i:s", time());
				}
				
				Db::startTrans();
				
//				排序字段存在
				if( isset($newData['sort']) ){
					$checkSortWhere[] = ['level', 'eq', $newData['level']];
					$checkSortWhere[] = ['parent_id', 'eq', $newData['parent_id']];
					$checkSortWhere[] = ['sort', 'eq', $newData['sort']];
					$checkSort = Db::table("gd_classification") -> where($checkSortWhere) -> find();
					if( !empty($checkSort) ){
						$sortWhere[] = ['level', 'eq', $newData['level']];
						$sortWhere[] = ['parent_id', 'eq', $newData['parent_id']];
						$all = Db::table("gd_classification") -> where($sortWhere) -> select();
						if( !empty($all) ){
	//						判断是否重叠
							foreach($all as $k => $v){
								if( $newData['sort'] > $v['sort'] ) {
									unset($all[$k]);
								}else{
	//								重叠，后面的数据全部往后移动一位
									$incRe = Db::table("gd_classification") -> where(['id'=>$v['id']]) -> setInc('sort', 1);
									if( !$incRe ) {
										Db::rollback();
										returnResults2('-1', '变更排序失败,请联系管理员');
									}
								}
							}
						}
					}
				}else{
//					排序字段不存在，查询已有最大的排序值
//					$maxSort = Db::table("gd_classification") -> max("sort");
				}
				
				
				$re = Db::table("gd_classification") -> insertGetId($newData);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '新增失败,请联系管理员');
				}
				Db::commit();
				$outArr['code'] = '1';
				$outArr['info'] = $re;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'新增分类',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 树形结构
	 */	
	public function tree($data, $pk = 'id', $pid = 'parent_id', $child = 'children', $root = 0){
//		创建Tree
		$tree = [];
		if (!is_array($data)) {
		    return false;
		}
          
//		创建基于主键的数组引用
        $refer = [];
        foreach ($data as $key => $value_data) {
            $refer[$value_data[$pk]] = &$data[$key];
        }
        foreach ($data as $key => $value_data) {
//			判断是否存在parent
            $parentId = $value_data[$pid];
            if ($root == $parentId) {
                $tree[] = &$data[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][] = &$data[$key];
                }
            }
        }
        return $tree;
	}
	
}

?>